package com.itheima.cloud.user.service;

import com.itheima.cloud.pojo.Order;
import com.itheima.cloud.pojo.User;
import com.itheima.cloud.response.OrderVo;
import com.itheima.cloud.response.UserOrderVo;
import com.itheima.cloud.user.client.OrderClient;
import com.itheima.cloud.user.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dozer.Mapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
@Slf4j
public class UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    OrderClient orderClient;

    @Autowired
    Mapper dozerMapper;


    public User findUser(String username) {
        // 网关 -> 认证服务 -> 用户信息存储到redis. -> 解析JWT令牌得到用户信息
        return   userMapper.selectByPrimaryKey(username);
    }


    public UserOrderVo findOrderByUserId(String username) {  // {user, list}
        // 1 参数校验
        if (StringUtils.isBlank(username)) {
            throw new RuntimeException("参数非法");
        }

        // 2 业务
        // 2.1 查询用户信息
        User user = this.findUser(username);
        if (user == null) {
            log.error("无当前用户信息");
            throw new RuntimeException("无当前用户信息");
        }
        // 2.2 根据用户名查询订单列表， 基于feign
        List<Order> orderList = orderClient.findOrder(user.getUsername());


        // 3 结果处理封装
//        Map map = new HashMap();
//        map.put("user", user);
//        map.put("orders", orderList);

        UserOrderVo userOrderVo = new UserOrderVo();
//        userOrderVo.setUsername(user.getUsername());
//        userOrderVo.setNickName(user.getNickName());

        // MapStruct, Dozer  java对象和O之间的转换
//        BeanUtils.copyProperties(user,userOrderVo );

        userOrderVo = dozerMapper.map(user, UserOrderVo.class);


        List<OrderVo> orderVoList = new ArrayList<>();
        for (Order order : orderList) {
            OrderVo orderVo = new OrderVo();
            BeanUtils.copyProperties(order, orderVo);
            orderVoList.add(orderVo);
        }
        userOrderVo.setOrderList(orderVoList);

        return userOrderVo;
    }

}
